package com.catalina.serviceImpl;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.catalina.dao.UserDao;
import com.catalina.entity.User;
import com.catalina.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	// 初始化spring容器
	// ApplicationContext context = new
	// ClassPathXmlApplicationContext("spring-mybatis.xml");

	// UserDao userDao = (UserDao) context.getBean("userDao");

	@Autowired
	private UserDao userDao;
	private Workbook workbook;

	@Override
	public User select(String name, String password) {
		User user = userDao.select(name, password);
		return user;
	}

	public void insert(User user) {
		userDao.insert(user);
	}

	public void update(User user) {
		userDao.update(user);
	}

	public void delete(int id) {
		userDao.deleteByPrimaryKey(id);
	}

	@Override
	public List<User> selectList(String sort, String order) {//得到全部数据
		List<User> users = userDao.selectAllUser(sort, order);
		return users;
	}

	@Override
	public Integer getTotal(String name) {//得到总数
		Integer num = userDao.selectAllUserNumber(name);
		return num;
	}

	@Override
	public List<User> selectList(Integer page, Integer rows, String name, String sort, String order) {//得到datagrid数据
		Integer start = (page - 1) * rows;
		List<User> users = userDao.selectPageUser(start, rows, name, sort, order);
		return users;
	}

	@Override
	public Integer deleteList(String str) {
		String[] arrStr = str.split(",");
		Integer[] arrInt = new Integer[arrStr.length];
		for (int i = 0; i < arrStr.length; i++) {
			arrInt[i] = Integer.parseInt(arrStr[i]);
		}
		Integer num = userDao.deleteList(arrInt);
		return num;

	}

	public Workbook exportToExcel(String[] title, String fileName, List<User> userList) throws IOException {
		workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet("uers");
		Row row = sheet.createRow(0);

		Cell cell;
		for (Integer i = 0; i < title.length; i++) {
			cell = row.createCell(i);
			cell.setCellValue(title[i]);
		}

		Iterator<User> users = userList.iterator();

		Integer rowIndex = 0;
		while (users.hasNext()) {
			User user = users.next();
			row = sheet.createRow(++rowIndex);
			cell = row.createCell(0);
			cell.setCellValue(user.getUsername());
			cell = row.createCell(1);
			cell.setCellValue(user.getPassword());
			cell = row.createCell(2);
			cell.setCellValue(user.getAge());
		}
		return workbook;

	}

}
